import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    value: '',
    suggestList: [],
    setId: 0,
    history: []
  }

  config = {
  }

  methods = {
    onChange (e) {
      this.value = e.detail.trim()
      // 实现搜索功能
      clearTimeout(this.setId)
      if (this.value === '') return this.suggestList = []
      this.setId = setTimeout(async () => {
        const {data:res} = await wepy.get('/goods/qsearch',{
          query: this.value
        })
        if (res.meta.status !== 200) return wepy.baseToast()
        this.suggestList = res.message
        this.$apply() 
      },800)
    },
    onSearch () {
      clearTimeout(this.setId)
      if (this.value === '') return
      if (this.history.indexOf(this.value) === -1) {
        this.history.unshift(this.value)
        this.history = this.history.slice(0,10)
        wepy.setStorageSync('history',this.history)
      }
      wepy.navigateTo({
        url: '/pages/goods_list?query=' + this.value
      })
    },
    removeHistory () {
      this.history = []
      wepy.setStorageSync('history',this.history)
    }
  }
  onLoad () {
    this.history = wepy.getStorageSync('history') || []
  }
  onHide () {
    this.value = ''
    this.suggestList = []
  }
  onShow () {
    this.$parent.setTabbatBadge()
  }
}
